package club.xyes.pi4j.controller;

import club.xyes.pi4j.i2c.PrettyIICDevice;
import club.xyes.pi4j.i2c.SSD1306Device;
import club.xyes.pi4j.util.RadixUtil;
import club.xyes.pi4j.vo.BasicJsonResult;
import com.pi4j.io.i2c.I2CBus;
import com.pi4j.io.i2c.I2CDevice;
import com.pi4j.io.i2c.I2CFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

/**
 * 2018/11/6 Create by 郭文梁
 * IICController
 * IIC访问控制器
 *
 * @author 郭文梁
 * @date 2018/11/6
 */
@RestController
@RequestMapping("/iic")
public class IICController {
    /**
     * iic设备地址
     */
    private static final int ADDRESS = 0x3C;
    /**
     * iic总线
     */
    private static I2CBus bus;
    private static PrettyIICDevice device;
    private static SSD1306Device ssd1306;

    /**
     * 初始化iic设备
     *
     * @return json
     * @throws IOException                              IOE
     * @throws I2CFactory.UnsupportedBusNumberException 总线不支持
     */
    @GetMapping("/init")
    public BasicJsonResult init() throws IOException, I2CFactory.UnsupportedBusNumberException {
        bus = I2CFactory.getInstance(I2CBus.BUS_1);
        I2CDevice d = bus.getDevice(ADDRESS);
        device = new PrettyIICDevice(d);
        ssd1306 = new SSD1306Device(device);
        return BasicJsonResult.ok();
    }

    /**
     * 向IIC设备发送数据
     *
     * @param hex 十六进制字符串 例：A7
     * @return JSON
     * @throws IOException IOE
     */
    @GetMapping("/send")
    public BasicJsonResult send(String hex) throws IOException {
        int data = RadixUtil.fromHex(hex);
        device.write(data);
        return BasicJsonResult.ok();
    }

    /**
     * 重置总线
     *
     * @return json
     * @throws IOException IOE
     */
    @GetMapping("/reset")
    public BasicJsonResult reset() throws IOException {
        bus.close();
        device = null;
        bus = null;
        return BasicJsonResult.ok();
    }

    /**
     * 初始化SSD1306
     *
     * @return JSON
     * @throws IOException IOE
     */
    @GetMapping("/init-ssd1306")
    public BasicJsonResult initSSD1306() throws IOException {
        ssd1306.init();
        return BasicJsonResult.ok();
    }

    /**
     * 测试显示
     *
     * @return json
     * @throws IOException ioe
     */
    @GetMapping("/print")
    public BasicJsonResult print() throws IOException {
        for (int i = 0; i < 128; i++) {
            ssd1306.writeData(0xAA);
        }
        return BasicJsonResult.ok();
    }
}









